package com.beep.erp.model.update.service;

import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;

import com.beep.erp.BuildConfig;
import com.beep.erp.Constants;
import com.beep.erp.R;
import com.beep.erp.common.utils.ToastUtils;
import com.beep.erp.common.utils.ToolsUtils;
import com.beep.erp.model.update.fileload.FileCallback;
import com.beep.erp.model.update.fileload.FileResponseBody;
import com.beep.erp.model.update.fileload.IFileLoad;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.beep.erp.http.HttpRetrofit.DEFAULT_TIMEOUT;

/**
 * FileName: DownLoadService
 * description: 自动下载更新服务
 */
public class DownLoadService extends Service {

    /**
     * 目标文件存储的文件夹路径
     */
    private String  destFileDir = "";
    /**
     * 目标文件存储的文件名
     */
    private String destFileName = "presaint.apk";
    private Context mContext;
    private static int preProgress = 0;
    private static int NOTIFY_ID = 1000;
    private String url = "";
    public static NotificationCompat.Builder builder;
    public static NotificationManager notificationManager;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mContext = this;
        destFileDir=mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+"";
        if(!ToolsUtils.isEmpty(intent.getExtras().getString(Constants.BUNDLE_KEY_TITLE,""))){
            url=intent.getStringExtra(Constants.BUNDLE_KEY_TITLE);
            loadFile();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 下载文件
     */
    private void loadFile() {
        initNotification();
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        builder.networkInterceptors().add(chain -> {
            Response originalResponse = chain.proceed(chain.request());
            return originalResponse
                    .newBuilder()
                    .body(new FileResponseBody(originalResponse))
                    .build();
        });
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").serializeNulls().create();
        Retrofit retrofit = new Retrofit.Builder()
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create(gson)) //  添加数据解析ConverterFactory
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) //添加RxJava
                .baseUrl(Constants.API_URL)
                .build();
        IFileLoad iFileLoad=retrofit.create(IFileLoad.class);
        Call<ResponseBody> responseBodyCall =iFileLoad.loadFile(url);
        responseBodyCall.enqueue(new FileCallback(destFileDir, destFileName) {
            @Override
            public void onSuccess(File file) {
                Log.e("zs", "请求成功");
                // 安装软件
                installApk(file);
            }

            @Override
            public void onLoading(long progress, long total) {
                Log.e("zs", progress + "----" + total);
                updateNotification(progress * 100 / total);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.e("zs", "请求失败"+t.getMessage());
                ToastUtils.showShort("更新失败");
                cancelNotification();
            }
        });
    }


    /**
     * 安装软件
     *
     * @param file
     */
    private void installApk(File file) {
        Uri uri = Uri.fromFile(file);
        Intent install = new Intent(Intent.ACTION_VIEW);
        if(Build.VERSION.SDK_INT > 23){
            uri = FileProvider.getUriForFile(this,
                    BuildConfig.APPLICATION_ID , file);
        }
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        install.setDataAndType(uri, "application/vnd.android.package-archive");
        // 执行意图进行安装
//        HomeViewPageFragment.pos=0;
        mContext.startActivity(install);
        cancelNotification();
    }


    /**
     * 初始化Notification通知
     */
    public void initNotification() {

        builder = new NotificationCompat.Builder(mContext)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentText(preProgress+"%")
                .setContentTitle("未来无限正在更新")
                .setProgress(100, 0, false);
        notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFY_ID, builder.build());
    }

    /**
     * 更新通知
     */
    public static void updateNotification(long progress) {
        int currProgress = (int) progress;
        if (preProgress < currProgress) {
            builder.setContentText(progress + "%");
            builder.setProgress(100, (int) progress, false);
            notificationManager.notify(NOTIFY_ID, builder.build());
        }
        preProgress = (int) progress;
    }

    /**
     * 取消通知
     */
    public void cancelNotification() {
        notificationManager.cancel(NOTIFY_ID);
    }
}
